//
//  SEPrescriptionTemplateListController.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/6/9.
//

import UIKit

class SEPrescriptionTemplateListController: SEBaseViewController {
    
    private var viewModel = SEPrescriptionViewModel()
    
    var pickHandler: ((String, Bool) -> Void)?
    
    convenience init(isPick: Bool = false) {
        self.init()
        self.viewModel.isPick = isPick
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        viewModel.updateData = { [weak self] status in
            self?.tableView.se_empty?.allowShow = true
            self?.endRefreshing()
            switch status {
            case .success:
                self?.tableView.reloadData()
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.loadData))
            case .failure: break
            }
        }
    }
    
    override func setupUI() {
        title = "处方模板"
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview().priority(.low)
            make.top.equalTo(view.safeAreaLayoutGuide)
        }
    }
    
    override func setupNavBar() {
        super.setupNavBar()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "添加", target: self, action: #selector(addTemplateTapped))
    }
    
    // MARK: - getter
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .background
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.se_header = SERefreshHeader { [weak self] in self?.loadData() }
        tableView.se_header?.beginRefreshing()
        tableView.se_footer = SERefreshFooter { [weak self] in self?.loadData(more: true) }
        tableView.se_empty = SEEmptyView { [weak self] in self?.tableView.se_header?.beginRefreshing() }
        
        tableView.register(SEPrescriptionTemplateListCell.nibForCell(),
                           forCellReuseIdentifier: SEPrescriptionTemplateListCell.reuseIdentifier())
        
        return tableView
    }()

}

extension SEPrescriptionTemplateListController {
    @objc private func loadData(more: Bool = false) {
        viewModel.getListOfPrescriptionTemplate(more)
    }
    
    private func endRefreshing() {
        tableView.endHeaderRefreshing()
        tableView.endFooterRefreshing(hasMore: viewModel.hasMore)
    }
    
    @objc private func addTemplateTapped() {
        let mode = SEPrescriptionMode.template("", true)
        let vc = SEPrescriptionNewViewController(mode: mode)
        navigationController?.pushViewController(vc, animated: true)
        
        vc.updateHandler = { self.loadData() }
    }
}

// MARK: - UITableViewDataSource

extension SEPrescriptionTemplateListController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SEPrescriptionTemplateListCell.reuseIdentifier(), for: indexPath) as! SEPrescriptionTemplateListCell
        cell.update(with: viewModel.viewModel(at: indexPath))
        return cell
    }
}

// MARK: - UITableViewDelegate

extension SEPrescriptionTemplateListController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 94
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vm = viewModel.viewModel(at: indexPath)
        guard let id = vm.prescription.id else { return }
        
        if viewModel.isPick {
            pickHandler?(id, viewModel.isPick)
            navigationController?.popViewController(animated: true)
        } else {
            let mode = SEPrescriptionMode.template(id, false)
            let vc = SEPrescriptionNewViewController(mode: mode)
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        switch editingStyle {
        case .delete:
            // 删除处方模版
            viewModel.deleteePrescriptionTemplate(indexPath: indexPath, successComplete: { [weak self] in
                guard let self = self else { return }
                self.tableView.reloadData()
            })
        default:
            break
        }
    }
}
